<template>
  <div>
    <div class="mb-3">
      <query-form :params="params" @search="handleSearch" @reset="handleReset">
        <query-item :label="$t('model.name')" name="Q_Contains_name"></query-item>
      </query-form>
    </div>
    <div>
      <el-button type="primary" :disabled="perm('model:create')" icon="el-icon-plus" size="small" @click="handleAdd()">{{ $t('add') }}</el-button>
      <el-popconfirm :title="$t('confirmDelete')" @confirm="handleDelete(selection.map((row) => row.id))">
        <template #reference>
          <el-button :disabled="selection.length <= 0 || perm('model:delete')" icon="el-icon-delete" size="small">{{ $t('delete') }}</el-button>
        </template>
      </el-popconfirm>
      <list-move :disabled="selection.length <= 0 || filtered || perm('org:update')" @move="(type) => move(selection, type)" class="ml-2" />
      <column-setting name="model" class="ml-2" />
    </div>
    <el-radio-group v-model="modelType" @change="fetchData()" size="small" class="mt-3">
      <!-- ['article', 'channel', 'user', 'site', 'global'] -->
      <el-radio-button v-for="n in ['article', 'channel', 'site', 'global']" :key="n" :label="n">{{ $t(`model.type.${n}`) }}</el-radio-button>
    </el-radio-group>
    <div class="app-block">
      <el-table ref="table" v-loading="loading" :data="data" @selection-change="(rows) => (selection = rows)" @row-dblclick="(row) => handleEdit(row.id)" @sort-change="handleSort">
        <column-list name="model">
          <el-table-column type="selection" :selectable="deletable" width="45"></el-table-column>
          <el-table-column property="id" label="ID" width="60" sortable="custom"></el-table-column>
          <el-table-column property="name" :label="$t('model.name')" sortable="custom" show-overflow-tooltip></el-table-column>
          <el-table-column property="type" :label="$t('model.type')" sortable="custom" :formatter="(row) => $t(`model.type.${row.type}`)" />
          <el-table-column property="scope" :label="$t('model.scope')" sortable="custom" :formatter="(row) => $t(`model.scope.${row.scope}`)" />
          <el-table-column :label="$t('table.action')">
            <template #default="{row}">
              <el-space>
                <el-link type="primary" :disabled="perm('model:update')" @click="handleEdit(row.id)" class="text-xs" href="javascript:">{{ $t('edit') }}</el-link>
                <el-link
                  v-if="!['global', 'site'].includes(row.type)"
                  type="primary"
                  :disabled="perm('model:update')"
                  @click="handleSystemFields(row.id)"
                  class="text-xs"
                  href="javascript:"
                >
                  {{ $t('model.fun.systemFields') }}
                </el-link>
                <el-link type="primary" :disabled="perm('model:update')" @click="handleCustomFields(row.id)" class="text-xs" href="javascript:">
                  {{ $t('model.fun.customFields') }}
                </el-link>
                <el-popconfirm v-if="deletable(row)" :title="$t('confirmDelete')" @confirm="handleDelete([row.id])">
                  <template #reference>
                    <el-link type="primary" :disabled="perm('model:delete')" class="text-xs" href="javascript:">{{ $t('delete') }}</el-link>
                  </template>
                </el-popconfirm>
              </el-space>
            </template>
          </el-table-column>
        </column-list>
      </el-table>
    </div>
    <model-form v-model="formVisible" :beanId="beanId" :beanIds="beanIds" :modelType="modelType" @finished="fetchData" />
    <model-system-fields v-model="systemFieldsVisible" :beanId="beanId" />
    <model-custom-fields v-model="customFieldsVisible" :beanId="beanId" />
  </div>
</template>

<script lang="ts">
import { computed, defineComponent, onMounted, ref } from 'vue';
import { ElMessage } from 'element-plus';
import { useI18n } from 'vue-i18n';
import { perm } from '@/store/useCurrentUser';
import { moveList, toParams, resetParams } from '@/utils/common';
import { deleteModel, queryModelList, updateModelOrder } from '@/api/config';
import { ColumnList, ColumnSetting } from '@/components/TableList';
import { QueryForm, QueryItem } from '@/components/QueryForm';
import ListMove from '@/components/ListMove.vue';
import ModelForm from './ModelForm.vue';
import ModelSystemFields from './ModelSystemFields.vue';
import ModelCustomFields from './ModelCustomFields.vue';

export default defineComponent({
  components: { ModelForm, ColumnList, ColumnSetting, QueryForm, QueryItem, ListMove, ModelSystemFields, ModelCustomFields },
  setup() {
    const { t } = useI18n();
    const params = ref<any>({});
    const modelType = ref<string>('article');
    const sort = ref<any>(undefined);
    const table = ref<any>(null);
    const data = ref<Array<any>>([]);
    const selection = ref<Array<any>>([]);
    const loading = ref<boolean>(false);
    const formVisible = ref<boolean>(false);
    const systemFieldsVisible = ref<boolean>(false);
    const customFieldsVisible = ref<boolean>(false);
    const beanId = ref<number | null>(null);
    const beanIds = computed(() => data.value.map((row) => row.id));
    const filtered = ref<boolean>(false);
    const fetchData = async () => {
      loading.value = true;
      try {
        data.value = await queryModelList({ ...toParams(params.value), Q_EQ_type: modelType.value, Q_OrderBy: sort.value });
        filtered.value = Object.values(params.value).filter((v) => v !== undefined && v !== '').length > 0 || sort.value !== undefined;
      } finally {
        loading.value = false;
      }
    };
    onMounted(fetchData);

    const handleSort = ({ column, prop, order }: { column: any; prop: string; order: string }) => {
      if (prop) {
        sort.value = (column.sortBy ?? prop) + (order === 'descending' ? '_desc' : '');
      } else {
        sort.value = undefined;
      }
      fetchData();
    };
    const handleSearch = () => fetchData();
    const handleReset = () => {
      table.value.clearSort();
      resetParams(params.value);
      sort.value = undefined;
      fetchData();
    };

    const handleSystemFields = (id: number) => {
      beanId.value = id;
      systemFieldsVisible.value = true;
    };
    const handleCustomFields = (id: number) => {
      beanId.value = id;
      customFieldsVisible.value = true;
    };
    const handleAdd = () => {
      beanId.value = null;
      formVisible.value = true;
    };
    const handleEdit = (id: number) => {
      beanId.value = id;
      formVisible.value = true;
    };
    const handleDelete = async (ids: number[]) => {
      await deleteModel(ids);
      fetchData();
      ElMessage.success(t('success'));
    };
    const move = async (selected: any[], type: 'top' | 'up' | 'down' | 'bottom') => {
      const list = moveList(selected, data.value, type);
      await updateModelOrder(list.map((item) => item.id));
    };
    const deletable = (bean: any) => bean.id > 10;
    return {
      params,
      modelType,
      filtered,
      table,
      data,
      selection,
      loading,
      formVisible,
      systemFieldsVisible,
      customFieldsVisible,
      beanId,
      beanIds,
      handleSystemFields,
      handleCustomFields,
      handleAdd,
      handleEdit,
      handleDelete,
      handleSearch,
      handleSort,
      handleReset,
      fetchData,
      deletable,
      perm,
      move,
    };
  },
});
</script>
